//
//  SAProductChooseSeasonView.m
//  yidiantong
//
//  Created by 黄志刚 on 2020/10/15.
//

#import "SAProductChooseSeasonView.h"
#import "SAProductChooseColorCell.h"
#import "SAProductChooseColorModel.h"
#import "SAProductChooseColorHeaderView2.h"
#import "SAProductDeleteColorView.h"
#import "SAUnitAddAPI.h"
#import "SAUnitListAPI.h"
#import "SAAttrAddAPI.h"
#import "SAAttrListAPI.h"
#import "SAUnitDeleteAPI.h"
#import "SAAttrDeleteAPI.h"

@interface SAProductChooseSeasonView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate,HTTPAPIDelegate>

@property (nonatomic,strong) NSMutableArray  *dataArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic ,copy) NSString *type;
@property (nonatomic,strong) UILabel *hitLabel;
@property (nonatomic,strong) UILabel *hitLabel1;
@property (nonatomic,strong) NSString *nameStr;
@property(nonatomic ,copy) NSString *isDetail;
@property(nonatomic ,assign) NSInteger isDetailId;

@property(nonatomic ,strong) SAUnitAddAPI *unitAddAPI;
@property(nonatomic ,strong) SAUnitListAPI *unitListAPI;
@property(nonatomic ,strong) SAAttrAddAPI *attrAddAPI;
@property(nonatomic ,strong) SAAttrListAPI *attrListAPI;
@property(nonatomic ,strong) SAUnitDeleteAPI *unitDeleteAPI;
@property(nonatomic ,strong) SAAttrDeleteAPI *attrDeleteAPI;
@property (nonatomic ,assign) BOOL isClear;

@property (nonatomic, strong) UITextField *nameTextfiled;

@end

@implementation SAProductChooseSeasonView

+(instancetype)shareCornView
{
    SAProductChooseSeasonView * shareView = [[SAProductChooseSeasonView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

-(instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        [self creatUI];
    }
    return self;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.unitAddAPI == api) {
        [Prompt popPromptViewWithMsg:@"新增成功!" duration:2];
        self.isClear= YES;
        self.nameStr = @"";
        self.nameTextfiled.text = @"";
        [self loadData];
    }else if (self.attrAddAPI == api) {
        [Prompt popPromptViewWithMsg:@"新增成功!" duration:2];
        self.isClear= YES;
        self.nameStr = @"";
        self.nameTextfiled.text = @"";
        [self loadData];
    }else if (self.unitListAPI == api) {
        [self.dataArray removeAllObjects];
        for ( NSDictionary *dict in (NSArray *)data[@"data"]) {
            SAProductChooseColorList *model = [SAProductChooseColorList mj_objectWithKeyValues:dict];
            [self.dataArray addObject:model];
        }
        [_collectionView reloadData];
    }else if (self.attrListAPI == api) {
        [self.dataArray removeAllObjects];
        for ( NSDictionary *dict in (NSArray *)data[@"data"]) {
            SAProductChooseColorList *model = [SAProductChooseColorList mj_objectWithKeyValues:dict];
            NSLog(@"%@",model);
            [self.dataArray addObject:model];
        }
        for (SAProductChooseColorList *list in self.dataArray) {
            if ([self.isDetail isEqualToString:@"1"]) {
                if (list.attrId == self.isDetailId) {
                    list.check = YES;
                }else {
                    list.check = NO;
                }
            }
        }
        [_collectionView reloadData];
    } else if (self.unitDeleteAPI == api) {
        [self loadData];
        [Prompt popPromptViewWithMsg:@"删除成功!" duration:2];
    }else if (self.attrDeleteAPI == api) {
        [Prompt popPromptViewWithMsg:@"删除成功!" duration:2];
        [self loadData];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

#pragma mark - UITextFieldDelegate
- (void)textFieldEditChanged:(UITextField*)textField {

}


-(void)creatUI
{
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kScreenWidth, kScaleNum(157));
    [deleteBtn addTarget:self action:@selector(shareDissTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(157), kScreenWidth, kScreenHeight - kScaleNum(157))];
    backGroundView.backgroundColor = kColor(246, 246, 246, 1);
    backGroundView.userInteractionEnabled = YES;
    [self addSubview:backGroundView];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(kScreenWidth - kScaleNum(80), kScaleNum(0), kScaleNum(80), kScaleNum(36));
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.titleLabel.font = kFont(17);
    [backGroundView addSubview:confirmBtn];
    
    UIView *bgView = [[UIView alloc] initWithFrame:SARectMake(0, 36, kBaseScreenWidth, 36)];
    bgView.backgroundColor = [UIColor whiteColor];
    [backGroundView addSubview:bgView];
    
    UITextField *nameTextfiled = [[UITextField alloc] initWithFrame:SARectMake(22, 36, 200, 36)];
    nameTextfiled.autocapitalizationType = UITextAutocapitalizationTypeNone;
    nameTextfiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    nameTextfiled.font = kFont(17);
    nameTextfiled.delegate = self;
    nameTextfiled.keyboardType = UIKeyboardTypeDefault;
    [nameTextfiled setTintColor:kColor(188, 188, 188, 1)];
    [nameTextfiled setTextColor:kColor(0, 0, 0, 1)];
    [nameTextfiled addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.nameTextfiled = nameTextfiled;
    [backGroundView addSubview:nameTextfiled];
    
    UIButton * addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(70), kScaleNum(39), kScaleNum(60), kScaleNum(30));
    [addBtn setImage:[UIImage imageNamed:@"Shop_CellAdd"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backGroundView addSubview:addBtn];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    // flow.headerReferenceSize = CGSizeMake(0, 200);
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.itemSize = CGSizeMake(kScaleNum(60), kScaleNum(24));
    flow.minimumInteritemSpacing = 0;
    //    //设置每行之间的最小间隔
    flow.minimumLineSpacing = kScaleNum(10);
    //   flow.headerReferenceSize = CGSizeMake(size(80), size(80));
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(0), kScaleNum(72), kScreenWidth,kScreenHeight - kScaleNum(229)) collectionViewLayout:flow];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource=self;
    _collectionView.delegate=self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [backGroundView addSubview:_collectionView];
    [_collectionView registerClass:[SAProductChooseColorCell class] forCellWithReuseIdentifier:@"SAProductChooseColorCell"] ;
    [_collectionView registerClass:[SAProductChooseColorHeaderView2 class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductChooseColorHeaderView2"];
    
    _hitLabel = [[UILabel alloc] init];
    _hitLabel1 = [[UILabel alloc] init];
}

-(void)addBtnClick
{
    self.attrAddAPI.attrName = self.nameTextfiled.text;
    self.attrAddAPI.attrType = self.type;
    [self.attrAddAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)loadData:(NSMutableArray *)array andType:(NSString *)type andIsDetail:(NSString *)isDetail andIsDetailId:(NSInteger)isDetailId
{
    self.type = type;
    self.isDetail = isDetail;
    self.isDetailId = isDetailId;
    if ([type isEqualToString:@"1"]) {
        self.hitLabel.text = @"请输入季节名称";
        self.hitLabel1.text = @"长按可删除自定义季节";
    }else if ([_type isEqualToString:@"2"])
    {
        self.hitLabel.text = @"请输入品牌名称";
        self.hitLabel1.text = @"长按可删除自定义品牌";
    }else if ([_type isEqualToString:@"3"])
    {
        self.hitLabel.text = @"请输入性别";
        self.hitLabel1.text = @"长按可删除自定义性别";
    }else if ([_type isEqualToString:@"4"])
    {
        self.hitLabel.text = @"请输入类别名称";
        self.hitLabel1.text = @"长按可删除自定义类别";
    }else if ([_type isEqualToString:@"5"])
    {
        self.hitLabel.text = @"请输入成分含量名称";
        self.hitLabel1.text = @"长按可删除自定义成分含量";
    }else if ([_type isEqualToString:@"6"])
    {
        self.hitLabel.text = @"请输入执行标准名称";
        self.hitLabel1.text = @"长按可删除自定义执行标准";
    }else if ([_type isEqualToString:@"7"])
    {
        self.hitLabel.text = @"请输入安全类别名称";
        self.hitLabel1.text = @"长按可删除自定义安全类别";
    }else if ([_type isEqualToString:@"8"])
    {
        self.hitLabel.text = @"请输入质量等级名称";
        self.hitLabel1.text = @"长按可删除自定义质量等级";
    }else if ([_type isEqualToString:@"9"])
    {
        self.hitLabel.text = @"请输入洗涤方式名称";
        self.hitLabel1.text = @"长按可删除自定义洗涤方式";
    }else if ([_type isEqualToString:@"-1"])
    {
        self.hitLabel.text = @"请输入单位名称";
        self.hitLabel1.text = @"【长按】可删除自定义单位";
    }
    if (array.count > 0) {
        [self.dataArray addObjectsFromArray:array];
    }else
    {
        [self loadData];
    }
}

-(void)loadData {
    if ([self.type isEqualToString:@"-1"]) {
        [self.unitListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }else {
        self.attrListAPI.attrType = self.type;
        [self.attrListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier=@"SAProductChooseColorCell";
    SAProductChooseColorCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    SAProductChooseColorList *list = self.dataArray[indexPath.row];
    
    [cell loadData:list];
    if (indexPath.section == 0) {
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(moveCollectionViewCell:)];
        [cell addGestureRecognizer:longPress];
    }
    return cell;
    
}
#pragma mark - 手势事件
-(void)moveCollectionViewCell:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            CGPoint point = [gesture locationInView:self.collectionView];
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
            if (indexPath.section != 0) {
                return;
            }
            NSLog(@"%ld",indexPath.row);
            SAProductChooseColorList *list = self.dataArray[indexPath.row];
            
            SAProductDeleteColorView *deleteColorView= [SAProductDeleteColorView shareCornView];
            deleteColorView.deleteColorBlock = ^{
                
                self.attrDeleteAPI.attrId = [NSString stringWithFormat:@"%zd",list.attrId];
                self.attrDeleteAPI.attrType = self.type;
                [self.attrDeleteAPI sendRequestToServerWithActivityViewAndMask:POST];
            };
            
            [deleteColorView setString:list.attrName];
            
            UIViewController *VC = nil;
            [deleteColorView showView:VC];
            
            break;
        }
        case UIGestureRecognizerStateChanged: {
            
            break;
        }
        case UIGestureRecognizerStateEnded: {
            
        }
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    for (SAProductChooseColorList *list in self.dataArray) {
        list.check = NO;
    }
    SAProductChooseColorList *list = self.dataArray[indexPath.row];
    list.check = YES;
    [self.collectionView reloadData];
}

#pragma mark--UICollectionViewDelegateFlowLayout的协议方法

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(kScaleNum(10), kScaleNum(10),kScaleNum(10),kScaleNum(10));
}

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kScaleNum(kBaseScreenWidth), kScaleNum(36));
    
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //返回段头段尾视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        __weak typeof(self) weakSelf = self;
            SAProductChooseColorHeaderView2 *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductChooseColorHeaderView2" forIndexPath:indexPath];
        [headerView refreshWithTitle:@"自定义" Placeholder: weakSelf.hitLabel.text AndTip:weakSelf.hitLabel1.text];
            if (self.isClear == YES) {
                weakSelf.nameStr = @"";
                weakSelf.nameTextfiled.text = @"";
                weakSelf.isClear = NO;
            }
            return headerView;
    }
    return nil;
}

-(NSMutableArray *)dataArray
{
    if(_dataArray == nil)
    {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)showView:(UIViewController *)Sview
{
    if(Sview == nil){
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }else{
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent
{
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)confirmationTapEvent
{
    
    //    NSMutableArray *seleArray = [NSMutableArray new];
    //    for (SAProductChooseColorModel *model in self.dataArray) {
    //
    //        for ( SAProductChooseColorList *list in model.attrVOS) {
    //            if (list.check == YES) {
    //               [seleArray addObject:list];
    //            }
    //
    //        }
    //    }
    if (self.selectedBlock) {
        self.selectedBlock(self.dataArray);
    }
    
    [UIView animateWithDuration:0.5f animations:^{
        
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}

-(SAUnitAddAPI *)unitAddAPI {
    if (!_unitAddAPI) {
        _unitAddAPI = [SAUnitAddAPI apiWithDelegate:self];
    }
    return _unitAddAPI;
}

-(SAUnitListAPI *)unitListAPI {
    if (!_unitListAPI) {
        _unitListAPI = [SAUnitListAPI apiWithDelegate:self];
    }
    return _unitListAPI;
}

-(SAAttrAddAPI *)attrAddAPI {
    if (!_attrAddAPI) {
        _attrAddAPI = [SAAttrAddAPI apiWithDelegate:self];
    }
    return _attrAddAPI;
}

-(SAAttrListAPI *)attrListAPI {
    if (!_attrListAPI) {
        _attrListAPI = [SAAttrListAPI apiWithDelegate:self];
    }
    return _attrListAPI;
}

-(SAUnitDeleteAPI *)unitDeleteAPI {
    if (!_unitDeleteAPI) {
        _unitDeleteAPI = [SAUnitDeleteAPI apiWithDelegate:self];
    }
    return _unitDeleteAPI;
}

-(SAAttrDeleteAPI *)attrDeleteAPI {
    if (!_attrDeleteAPI) {
        _attrDeleteAPI = [SAAttrDeleteAPI apiWithDelegate:self];
    }
    return _attrDeleteAPI;
}

@end
